package com.djhu.newscollector.crawel.base;

import com.djhu.newscollector.core.Holder.JobHolder;
import com.djhu.newscollector.core.dispatch.JobDispatcher;
import com.djhu.newscollector.core.entity.Response;
import com.djhu.newscollector.core.job.BaseJob;
import com.djhu.newscollector.core.worker.Worker;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by zw on 2018/2/13.
 */
public class AyncCrawel implements Worker{

    private static Logger logger = LogManager.getLogger(AyncCrawel.class.getName());

    private JobDispatcher jobDispatcher;

    private JobHolder jobHolder;

    private Worker worker;

    private ExecutorService executor = Executors.newFixedThreadPool(10);

    private int worksize = 6;

    @Override
    public Response process(BaseJob job) {
        for (int i = 0;i<worksize;i++){
            Crawler crawler = new Crawler();
            crawler.setWorker(worker);
            crawler.setJobHolder(jobHolder);
            crawler.setJobDispatcher(jobDispatcher);
            executor.execute(new InnerRunable(crawler));
        }
        executor.shutdown();
        return null;
        //return null;
    }


    public static class InnerRunable implements Runnable{

        public InnerRunable(Worker worker) {
            this.worker = worker;
        }

        private Worker worker;
        @Override
        public void run() {
            worker.process(null);
        }

        public Worker getWorker() {
            return worker;
        }

        public void setWorker(Worker worker) {
            this.worker = worker;
        }
    }


    public JobDispatcher getJobDispatcher() {
        return jobDispatcher;
    }

    public void setJobDispatcher(JobDispatcher jobDispatcher) {
        this.jobDispatcher = jobDispatcher;
    }

    public JobHolder getJobHolder() {
        return jobHolder;
    }

    public void setJobHolder(JobHolder jobHolder) {
        this.jobHolder = jobHolder;
    }

    public Worker getWorker() {
        return worker;
    }

    public void setWorker(Worker worker) {
        this.worker = worker;
    }
}